<#import "../tpl/pageTep.ftl" as page>
<@page.pageBase currentMenu="活动管理">
<style>
    .button-large {
        font-size: 16px;
    }

    hr {
        border-color: #009688;
    }

    .webuploader-pick {
        background: none;
        padding: 0;
    }
</style>
<div class="xm-offline">
    <div class="row">
        <div class="panel">
            <div class="panel-header">
                <a href="/rest/manage/activity/toList">返回上一级</a>
            </div>
            <div class="panel-body">
            <#--form表单提交，相当于data-->
                <form id="addForm" class="form-horizontal" action="${basepath}/rest/manage/activity/insertActivity"
                      method="post">
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            活动名称：
                        </label>

                        <div class="controls">
                            <input type="text" data-rules="{required:true}"
                                   class="offline-name control-text span-width span8"
                                   name="name" placeholder="请输入活动名称">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            品牌商：
                        </label>

                        <div class="controls" id="brandSelect">
                            <input type="hidden" id="brand" name="brandID">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            活动要求：
                        </label>

                        <div class="controls  control-row-auto">
                            <textarea class="control-row4 input-large" name="demand" id="content"></textarea>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            开始日期：
                        </label>

                        <div class="controls">
                            <input type="text" style="width: 140px;" name="starTime"
                                   data-rules="{required : true,sid:只能取往后一天的日期}" data-messages="{required:'只能取往后一天的日期'}"
                                   id="beginTime" class="calendar offline-starTime" placeholder="请选择活动开始日期"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            结束日期：
                        </label>

                        <div class="controls">
                            <input type="text" style="width: 140px;" class="calendar  offline-endTime "
                                   name="endTime"
                                   data-rules="{required : true}" placeholder="请选择活动结束日期" id="endTime"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            活动预算：
                        </label>

                        <div class="controls">
                            <input type="text" data-rules="{number:true}"
                                   class="offline-budge control-text span-width span8" name="budge"
                                   placeholder="请输入活动预算"/>
                        </div>
                    </div>
                    <h3 class="offset2">活动图片
                        <a class="button button-primary pull-right" id="imagesBtn" style="height:20px;">上传图片</a>
                    </h3>
                    <hr>
                    <input type="hidden" class="picture1 control-text span-width " name="picture" id="picture"
                           data-rules="{required:true}">

                    <div id="imagesGrid" class="xm-grid">
                    </div>
                    <h3 class="offset2">商品信息
                        <a class="button button-primary pull-right" style="height:16px;" href="javascript:addProduct()">添加</a>
                    </h3>
                    <hr>
                    <input type="hidden" class="picture1 control-text span-width " name="productName"
                           data-rules="{required:true}">
                    <input type="hidden" class="picture1 control-text span-width " name="productCode" id="productCode1">

                    <div id="productGrid" class="xm-grid">
                    </div>
                    <div class="centered">
                        <a class="button  button-large  button-success" id="saveBtn">保存</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<#-----------------------------------------------添加商品信息的弹出框------------------------------------------->
<div id="addSpecContent" style="display:none;">
    <form id="addSpecForm" class="form-horizontal">
        <div class="row">
            <div class="control-group span16">
                <label class="control-label">商品名称：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="productName"
                           data-rules="{required : true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">条形码：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="productCode"
                           data-rules="{required : true}" name="productCode" readonly/>
                    <a id="addImgBtn" class="button button-min button-primary pull-right"
                       style="height:20px;margin-left: 10px;">上传</a>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------添加商品信息的弹出框------------------------------------------->
<script type="text/javascript">
    var Grid = BUI.Grid;
    var Store = BUI.Data.Store;
    var Data = BUI.Data;
    var Select = BUI.Select;
    var Calendar = BUI.Calendar;
    var addForm = new BUI.Form.Form({
        srcNode: '#addForm',
        submitType: 'ajax',
        callback: function (data) {
            if (data.success == true) {
                window.location.href = '/rest/manage/activity/toList';
            } else {
                alert(data.message);
            }

        }
    }).render();

    //点击保存按钮，判断
    $("#saveBtn").click(function () {
        var starTime = $(".offline-starTime").val(),
                endTime = $(".offline-endTime").val();
        if (addForm.isValid()) {
            if (starTime > endTime) {
                //结束日期要大于开始日期
                BUI.Message.Alert('结束日期要大于开始日期', function () {
                }, 'info');
            }
            else {
                addForm.ajaxSubmit();
            }
        } else {
            addForm.valid();
        }
    });

    //品牌商下拉查询
    var brandStore = new Data.Store({
        url: '/rest/manage/account/selectAllBrand',
        autoLoad: true,
        root: 'data'
    });
    var brandSelect = new Select.Select({
        render: '#brandSelect',
        valueField: '#brand',
        list: {
            itemTpl: '<li>{nickname}</li>',
            idField: 'id',
            elCls: 'bui-select-list'
        },
        store: brandStore
    });
    brandSelect.render();
    /*--------------------------产品规格列表  begin--------------------*/
    var img = '';
    var name1 = '';
    /**
     * 规格信息
     * @type {*[]}
     */

    var specColumns = [
        {
            title: '商品名称', dataIndex: 'productName', elCls: "center"
        },
        {
            title: '条形码', dataIndex: 'productCode', elCls: "center", renderer: function (data) {
            return '<img src="${basepath}/' + data + '" width="100px" height="100px"/>';

        }
        },
        {
            title: '操作', dataIndex: 'productName', elCls: "center", renderer: function (data) {
            return '<a href="javascript:delSpec(\'' + data + '\')">删除</a>';
        }
        }
    ];
    var specStore = new Store({});
    var specGrid = new Grid.Grid({
        render: '#productGrid',
        forceFit: true,
        columns: specColumns,
        store: specStore
    });
    specGrid.render();
    $("#productName1").val(img);
    $("#productCode1").val(name1);
    /**
     * 删除规格信息--不是放在数据库中，而是显示在列表上的用bui的remove实现
     * @param index
     */
    function delSpec(productName) {
        var record = specStore.find('productName', productName);
        specStore.remove(record);
    }
    /*--------------------------产品规格列表  end---------------------------*/
    /*----------------------------------------------新增表单处理 begin------------------------------------*/
    var specs = specStore.getResult();
    var addSpecForm = new BUI.Form.Form({
        srcNode: '#addSpecForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            store.load(obj);
            addSpecForm.close();
        }
    }).render();

    var addProductDialog = new BUI.Overlay.Dialog({
        title: '新增商品信息',
        width: 500,
        height: 200,
        contentId: 'addSpecContent',
        success: function () {
            this.close();
            if (addSpecForm.isValid()) {
                addSpecs();
                this.close();
            } else {
                addSpecForm.valid();
            }
        }
    });
    //新增商品规格--先存入表单中，不直接存入数据库
    function addSpecs() {

        var spec = {
            "productName": $('#productName').val(),
            "productCode": $('#productCode').val()
        };
        specStore.add(spec);
        var productNameArr = [],
                productCodeArr = [];

        for (var i = 0; i < specs.length; i++) {
            productNameArr[i] = specs[i].productName;
            productCodeArr[i] = specs[i].productCode;
        }
        $("input[name='productName']").val(productNameArr.join(","));
        $("input[name='productCode']").val(productCodeArr.join(","));
    }
    /**
     *规格新增按钮事件
     */
    function addProduct() {
        $('#productName').val("");
        $('#productCode').val("");
        addSpecForm.clearErrors();//清楚第一次填写的内容
        addProductDialog.show();
        var addUploader = WebUploader.create({
            auto: true,
            swf: '${staticpath}/ueditor/third-party/webuploader/Uploader.swf',
            server: '${basepath}/rest/manage/ued/config?action=uploadimage',
            pick: '#addImgBtn',
            resize: false,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
            }
        });
        addUploader.on('uploadSuccess', function (file, response) {
            addUploader.removeFile(file);
            addSpecForm.setFieldValue("productCode", response.url)
        });
    }
    /*----------------------------------------------新增表单处理 end------------------------------------*/
    /*--------------------------活动图片列表  begin--------------------*/
    /**
     * 图片信息
     * @type {*[]}
     */
    var imagesColumns = [
        {
            title: '图片', dataIndex: 'url', width: '30%', renderer: function (data) {
            return '<img src="${basepath}/' + data + '" width="100px" height="100px"/>'
        }
        },
        {
            title: '状态', dataIndex: 'state', width: '30%', renderer: function (data) {
            if (data == "SUCCESS") {
                return "上传成功";
            }
            return "上传失败";
        }
        },
        {
            title: '操作', dataIndex: 'title', width: '40%', renderer: function (data, obj, index) {
            return '<a href="javascript:delImages(' + index + ')">删除</a>';
        }
        }
    ];
    /**
     * 删除缓存图片信息
     * @param index
     */
    function delImages(index) {
        var record = imagesStore.findByIndex(index);
        imagesStore.remove(record);
        var imgStr = imagesStore.getResult();
        var imgArr = new Array();
        for (var i = 0; i < imgStr.length; i++) {
            imgArr[i] = imgStr[i].url;
        }
        $("#picture").val(imgArr.join(","));
    }
    var imagesStore = new Store({});
    var imagesGrid = new Grid.Grid({
        render: '#imagesGrid',
        width: '100%',//如果表格使用百分比，这个属性一定要设置
        columns: imagesColumns,
        idField: 'title',
        store: imagesStore
    });
    imagesGrid.render();
    /*--------------------------活动图片列表  end--------------------*/

    /*------------------------图片上传插件配置  begin-----------------------*/
    var uploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#imagesBtn',//绑定事件
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });
    var imgs = imagesStore.getResult();
    uploader.on('uploadSuccess', function (file, response) {
        uploader.removeFile(file);//删除缓存
        if (imgs.length > 2) {
            BUI.Message.Alert('不能多于三张图片', function () {
            }, 'info');
        } else {
            imagesStore.add(response);//给store赋值
            //将数据源store转化成字符串赋值给input
            var imgArr = new Array();
            for (var i = 0; i < imgs.length; i++) {
                imgArr[i] = imgs[i].url
            }
            $("#picture").val(imgArr.join(","));
        }
    });
    /*------------------------图片上传插件配置  end-----------------------*/

</script>

</@page.pageBase>